/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.binding;

import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;

import java.util.*;

/**
 * 映射器注册表
 *
 * @author Clinton Begin
 * @author Eduardo Macarron
 * @author Lasse Voss
 */
public class MapperRegistry {

    private final Configuration config;
    // 已知的代理映射，维护了Mapper接口和代理类的映射关系，mapper接口类->MapperProxyFactory对象
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public MapperRegistry(Configuration config) {
        this.config = config;
    }

    /**
     * 获取映射器
     *
     * @param type       需要获取的映射器类型
     * @param sqlSession 会话
     * @param <T>        泛型
     * @return 映射器
     */
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        // 从缓存获取映射器代理对象
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);

        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
            // 通过代理工厂实例化映射器实例
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }

    /**
     * 加载指定类型的映射器
     *
     * @param type 映射器类型
     */
    public <T> void addMapper(Class<T> type) {

        if (type.isInterface()) {
            // 只处理接口
            if (hasMapper(type)) {
                // 只处理一次
                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                // 放入已知的代理映射中，mapper接口->MapperProxyFactory代理对象
                knownMappers.put(type, new MapperProxyFactory<T>(type));
                // 在运行解析器之前添加类型非常重要.
                // 否则,映射器解析器可能会自动尝试绑定。
                // 如果类型已知，则不会尝试
                // 解析注解
                MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
                // 执行解析
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    // 移除解析出现异常的接口
                    knownMappers.remove(type);
                }
            }
        }
    }

    /**
     * @since 3.2.2
     */
    public Collection<Class<?>> getMappers() {
        return Collections.unmodifiableCollection(knownMappers.keySet());
    }

    /**
     * 根据基础包名和父类/接口限制,批量注册映射器
     *
     * @since 3.2.2
     */
    public void addMappers(String packageName, Class<?> superType) {
        ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
        // 加载指定包下的继承/实现了指定类型的所有类
        resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
        Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
        for (Class<?> mapperClass : mapperSet) {
            // 执行映射器的注册操作
            addMapper(mapperClass);
        }
    }

    /**
     * 根据基础包名,批量注册映射器
     *
     * @since 3.2.2
     */
    public void addMappers(String packageName) {
        // 注册指定包下所有的java类
        addMappers(packageName, Object.class);
    }

}
